package com.vs.meepet.network.ext

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlin.coroutines.cancellation.CancellationException

/**
 *
 * 作者：柯嘉少
 * 邮箱：2449926649@qq.com
 * 日期: 2024/6/17
 * 修改人: xxx(des)
 * 说明:请求直接支持到协程的scope
 * 版本: 1.0
 */
fun <T> CoroutineScope.netRequest(block: RequestAction<T>.() -> Unit) {
    val action = RequestAction<T>().apply(block)
    this.launch(Dispatchers.IO) {
        try {
            action.start?.invoke()
            val result = action.request?.invoke()
            if (result != null && result.isSuccess()) {
                launch(Dispatchers.Main) {
                    action.success?.invoke(result!!.data)
                }
            } else {
                launch(Dispatchers.Main) {
                    action.error?.invoke(result!!.msg)
                    action.errorWithCode?.invoke(result!!.code, result!!.msg)
                }
            }
        } catch (ex: Exception) {
            if (ex is CancellationException) {//请求被取消的时候，不需要提示语，msg为空字符窜
                launch(Dispatchers.Main) {
                    action.error?.invoke("")
                    action.errorWithCode?.invoke(404, "")
                }
            } else {
                // 可以做一些定制化的返回错误提示
                launch(Dispatchers.Main) {
                    action.error?.invoke(ex.message ?: "")
                    action.errorWithCode?.invoke(404, ex.message ?: "")
                }
            }
        } finally {
            launch(Dispatchers.Main) {
                action.finish?.invoke()
            }
        }
    }
}